import { message } from 'antd';

export async function handleAction<T>(
  data: T,
  action: (data: T) => Promise<Record<string, any>>,
  actionName: string,
) {
  const hide = message.loading(`正在${actionName}`);
  try {
    await action(data);
    hide();
    message.success(`${actionName}成功`);
    return true;
  } catch (error) {
    hide();
    message.error(`${actionName}失败`);
    return false;
  }
}

export const handleAdd = async (
  data: AnyFields,
  action: (data: AnyFields) => Promise<Record<string, any>>,
) => {
  return handleAction<AnyFields>(data, action, '新增');
};

export const handleUpdate = async (
  data: AnyFields,
  action: (data: AnyFields) => Promise<Record<string, any>>,
) => {
  if (!data.id) {
    message.error(`更新失败`);
    return false;
  }
  return handleAction<AnyFields>(data, action, '更新');
};

export async function handleRemove(
  ids: string,
  action: (ids: string) => Promise<Record<string, any>>,
) {
  if (!ids) return true;
  return handleAction<string>(ids, action, '删除');
}
